﻿Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

Partial Class BigDecimal
  Implements ICloneable

  Public Function Clone() As Object Implements System.ICloneable.Clone
    Return CType(CloneObject(Me), BigDecimal)
  End Function

  Protected Friend Shared Function CloneObject(Of T)(ByVal obj As T) As T
    ' Create a memory stream and a formatter.
    Dim ms As New MemoryStream(1024)
    Dim bf As New BinaryFormatter()
    ' Serialize the object into the stream.
    bf.Serialize(ms, obj)
    ' Position streem pointer back to first byte.
    ms.Seek(0, SeekOrigin.Begin)
    ' Deserialize into another object.
    CloneObject = DirectCast(bf.Deserialize(ms), T)
    ' Release memory.
    ms.Close()
  End Function
End Class

Partial Class BigDecimal
 Implements IComparable(Of BigDecimal)
 Implements IComparer(Of BigDecimal)

 Public Function Compare(ByVal X As BigDecimal, ByVal Y As BigDecimal) As Integer Implements System.Collections.Generic.IComparer(Of BigDecimal).Compare
  If X.IsntNull AndAlso Y.IsntNull Then
   Select X.Sign.CompareTo(Y.Sign)
    Case -1
     ' X < Y
     Return -1
    Case 1
     ' Y < X
     Return 1
    Case Else
     ' They are of the Same Sign 
     ' So Further work is needed

     ' Are the DP the same
          Select Case X.DecimalPoint.CompareTo(Y.DecimalPoint)
            Case 0
              ' Same Place
              Return X.Digits.CompareTo(Y.Digits)
            Case -1
              ' X is further right
              Return X.AlignedTo(Y).Digits.CompareTo(Y.Digits)
            Case Else
              ' Y is further right
              Return X.Digits.CompareTo(Y.AlignedTo(X).Digits)
          End Select
   End Select
  Else
   Throw New ArgumentNullException

  End If
 End Function

 Public Function CompareTo(ByVal other As BigDecimal) As Integer Implements System.IComparable(Of BigDecimal).CompareTo
  Return Compare(Me, other)
 End Function
End Class